from django.db import models
from frame_server.model import BaseModel
from dict.models import Dict

# 菜单
class Menu(BaseModel):
    parentId = models.ForeignKey(to='self', db_column="parent_id", db_constraint=False, on_delete=models.CASCADE, null=True, blank=True, verbose_name="父级菜单")
    code = models.CharField(max_length=255,null=True,blank=True, verbose_name="菜单编号")
    name = models.CharField(max_length=255,null=True,blank=True, verbose_name="菜单名称")
    alias = models.CharField(max_length=255,null=True,blank=True, verbose_name="菜单别名")
    path = models.CharField(max_length=255,null=True,blank=True, verbose_name="请求地址")
    source = models.CharField(max_length=255,null=True,blank=True, verbose_name="字体图标名")
    sort = models.PositiveIntegerField(null=True,blank=True, verbose_name="排序")
    category = models.SmallIntegerField(null=True,blank=True, verbose_name="菜单类型（1菜单，2按钮）") 
    action = models.SmallIntegerField(null=True,blank=True,default=0, verbose_name="操作按钮类型") 
    remark = models.CharField(max_length=255,null=True,blank=True, verbose_name="备注") 
    
    class Meta:
        db_table = 'system_menu'
        ordering = ['sort','-createTime']
        indexes = [
            models.Index(fields=['parentId']),
            models.Index(fields=['code']),
            models.Index(fields=['name']),
            models.Index(fields=['category']),
            models.Index(fields=['action']),
        ]
        constraints = [
            models.UniqueConstraint(fields=['code','name'], name="%(app_label)s_%(class)s_code_name",violation_error_message="菜单编号和名称已存在"),
        ]

    def __str__(self):
        return self.name

    @property
    def categoryName(self):
        dicts = Dict.objects.filter(code='menu_category', dictValue__isnull=False).values('dictText','dictValue')
        if dicts.exists():
            return filter(lambda x:int(x['dictValue']) == self.category, dicts).__next__()['dictText']
        return None